package com.hongye.why.base.listenin;

import android.util.Log;

/**
 * 其他线程的消息派送
 */
final class OtherThreadMessagePoster implements Runnable {
    private final MessagePosterQueue queue;
    private volatile boolean executorRunning;
    private Listenin listenin;

    OtherThreadMessagePoster(Listenin listenin) {
        queue = new MessagePosterQueue();
        this.listenin = listenin;
    }

    public void enqueue(MessagePoster messagePoster) {
        synchronized (this) {
            this.queue.enqueue(messagePoster);
            if (!executorRunning) {
                this.executorRunning = true;
                listenin.executor.execute(this);
            }
        }
    }

    @Override
    public void run() {
        try {
            while (true) {
                MessagePoster poster = this.queue.poll(1000);
                if (poster == null) {
                    synchronized (this) {
                        poster = this.queue.poll();
                        if(poster == null) {
                            this.executorRunning = false;
                            return;
                        }
                    }
                }
                this.listenin.invokePoster(poster);
            }
        } catch (InterruptedException e) {
            Log.w("Event", Thread.currentThread().getName() + " was interruppted", e);
        } finally {
            this.executorRunning = false;
        }
    }
}
